package project.tool4nat.client.handler;

import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import project.tool4nat.common.ChannelManager;
import project.tool4nat.common.Constants;
import project.tool4nat.common.DataPack;

public class ContentServerHandler extends SimpleChannelInboundHandler<ByteBuf> {

    private final static Logger logger = LoggerFactory.getLogger(ContentServerHandler.class);

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        ChannelManager.removeCaller(ctx.channel().attr(Constants.CID_KEY).get());
        super.channelInactive(ctx);
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
        long cid = ctx.channel().attr(Constants.CID_KEY).get();
        byte[] data = new byte[msg.readableBytes()];
        msg.readBytes(data);
//        logger.info("receive msg from content server , cid={}\r\n{}", cid, new String(data));
        DataPack dataPack = new DataPack();
        dataPack.setCid(cid);
        dataPack.setData(data);
        Channel tunnel = ChannelManager.getProxyTunnel();
        if (tunnel != null) {
            tunnel.writeAndFlush(dataPack);
        }
    }
}
